/*
 *    Copyright 2022 The DSMS Authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dsms.common.prometheus.builder;

import com.dsms.common.util.PrometheusUtils;

import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class InstantQueryBuilder implements QueryBuilder {
    private static final String TARGET_URI_PATTERN_SUFFIX = "/api/v1/query?query=#{query}&time=#{time}&timeout=#{timeout}";

    private static final String TIME_EPOCH_TIME = "time";
    private static final String TIMEOUT = "timeout";
    private static final String QUERY_STRING = "query";

    private String targetUriPattern;
    private Map<String, Object> params = new HashMap<>();

    public InstantQueryBuilder(String prometheusUrl) {
        targetUriPattern = prometheusUrl + TARGET_URI_PATTERN_SUFFIX;
        params.put(TIMEOUT, "");
        params.put(TIME_EPOCH_TIME, "");
    }

    public InstantQueryBuilder withQuery(String query) {
        params.put(QUERY_STRING, URLEncoder.encode(query, StandardCharsets.UTF_8));
        return this;
    }

    public InstantQueryBuilder withEpochTime(long time) {
        params.put(TIME_EPOCH_TIME, time);
        return this;
    }


    public InstantQueryBuilder withTimeout(String timeout) {
        params.put(TIMEOUT, timeout);
        return this;
    }

    public URI build() {
        return URI.create(PrometheusUtils.namedFormat(targetUriPattern, params));
    }

}
